<?php
namespace Mobile\Controller;
use Mobile\Model\memberModel;
use Mobile\Model\keywordModel;
use Mobile\Model\tmpmsgModel;
use Mobile\Model\tmplModel;
use Mobile\Model\configModel;

class WeixinController extends WechatController
{

    public $keywordModel;
    public $memberModel;
    public $type;
    public $openid;
    public $wxuserinfo;//微信用户资料
    public $tmpl;
    public $configModel;
    
    
    public function __construct() {
        $this->_getConfig();//获取数据库配置文件
        //读取模板id并缓存
        $tmpl = S("TMPL");
        if(empty($tmpl) || 1){
            $tmpl = $this->_getTmpId();//获取模板id
            S("TMPL",$tmpl);
        }
        $this->tmpl = $tmpl;
    
        parent::__construct();
        $this->memberModel = new memberModel();
        $this->keywordModel = new keywordModel();
        //file_put_contents("weixin.txt", file_get_contents("php://input"));
         $this->valid();//明文或兼容模式可以在接口验证通过后注释此句，但加密模式一定不能注释，否则会验证失败
        $this->openid = $this->getRev()->getRevFrom();//openid
        $this->type = $this->getRev()->getRevType();//消息类型
    
    
    }
    
    //获取数据库中的模板消息id
    protected function _getTmpId(){
        $tmplModel = new tmplModel();
        $where = array(
    
        );
        $res = $tmplModel->getTmplList($where);
        $new = array();
        if(!empty($res)){
             
            foreach($res as $k=>$v){
                $new[$v['tmp_name']] = $v;
            }
             
        }
        return $new;
    }
    
    
    //获取数据库中的配置文件
    protected function _getConfig(){
        $this->configModel = new configModel();
        $where = array(
            "status" => 1,
        );
        $res = $this->configModel->getConfigList($where);
        if(!empty($res)){
            foreach($res as $k=>$v){
                C($v['cname'],$v['cvalue']);
            }
        }
        return true;
    }
    
    
    
    //首页
    public function rukou(){
        //$postStr = file_get_contents("php://input");
        //file_put_contents('wechat.txt', $postStr);
        //判断网站是否关闭
        $is_close  = C("IS_CLOSED");
        if($is_close == 1){
            //网站关闭
            $msg = C("CLOSED_REASON") ? C("CLOSED_REASON") : "网站暂时关闭,请联系客服";
            $this->text($msg)->reply();//回复消息
            exit;
        }
        
        //将最新的会员信息写入数据表
        
        $wxuser = $this->getUserInfo($this->openid);//从接口获取关注者信息
        if($wxuser){
            $wxinfo = $this->_get_member_wxinfo($wxuser);//组装信息
            $uid = $this->_add_member($wxinfo);//写入数据库
        }

        switch($this->type) {
            case "text":
                $content= $this->getRev()->getRevContent();//获取文本
                $res = $this->_receiveText($content);//文本消息处理
                break;
            case "image":
                $res = $this->_receiveImage();//图片消息处理
                break;
            case "event":
                $res = $this->_receiveEvent();//事件消息
                break;
            case "location":
                $res = $this->_receiveLocation();//地理位置消息
                break;
            case "voice":
                $res = $this->_receiveVoice();//语音消息
                break;
            case "video":
                $res = $this->_receiveVideo();//视频消息
                break;
            case "link":
                $res = $this->_receiveLink();//链接消息
                break;
            case "shortvideo":
                $res = $this->_receiveShortvideo();//链接消息
                break;
            default:
                $res = $this->text("hi,Unknown message type~");//未知消息类型
                
        }
        
        if($res){
            $res->reply();//回复消息
        }else{
            //无需回应
            echo "";exit;//输出空串
        }
        
    
    }
    
    
    
    /*
     * 更新用户资料
     */
    protected function _updateUserInfo($user_data){
         
        $openid = set_default($user_data,'openid');//联合id
        if(empty($user_data)){
            return false;
        }
        
        if(!$openid){
            return false;
        }

        $where = array(
            'openid' => $openid
        );

        $local_userinfo = $this->memberModel->getMember($where);
        
        if(isset($user_data['nickname'])){
            $user_data['nickname'] = str_replace(array(",","'","\"","\\","\/","`"),array("，","＂","＂","","",""),$user_data['nickname']);//转义
            $user_data['nickname'] = str_replace(array("\r\n", "\r", "\n"), "", $user_data['nickname']);
            $user_data['nickname'] = str_replace(PHP_EOL, '', $user_data['nickname']);
        }
        
        if($local_userinfo){
            //如果找到了,更新用户信息
            $user_data['last_login_ip'] = get_client_ip();
            $user_data['last_login_time'] = date("Y-m-d H:i:s");
            $user_data['login_times'] = array('exp','login_times+1');
            $res = $this->memberModel->editMember($where,$user_data);//更新
            
        }else{
            //没找到,添加
            
            $user_data['status'] = 1;
            $user_data['last_login_ip'] = get_client_ip();
            $user_data['last_login_time'] = date("Y-m-d H:i:s");
            $user_data['login_times'] = 1;
            $user_data['create_time'] = date("Y-m-d H:i:s");
            $user_data['role_id'] = 2;
            $user_data['is_change_username'] = 0;
            $res = $this->memberModel->addMember($user_data);
        }
        
    }


    //获取微信用户信息
    protected function _get_member_wxinfo($wxuser){
        $subscribe = set_default($wxuser,"subscribe");
        $openid = set_default($wxuser,"openid");
        
        //如果没有关注,只跟新基本信息
        if(!$subscribe){
            $user_data = array(
                "openid" => $openid,
                "subscribe" => set_default($wxuser,"subscribe"),
            );
        }else{
            //如果已经关注,更新全部信息
            $user_data = array(
                "openid" => $openid,
                "nickname" => set_default($wxuser,"nickname"),
                "sex" => set_default($wxuser,"sex"),
                "province" => set_default($wxuser,"province"),
                "city" => set_default($wxuser,"city"),
                "country" => set_default($wxuser,"country"),
                "privilege" => set_default($wxuser,"privilege"),
                "unionid" => set_default($wxuser,"unionid"),
                "groupid" => set_default($wxuser,"groupid"),
                "subscribe" => set_default($wxuser,"subscribe"),
                "language" => set_default($wxuser,"language"),
                "remark" => set_default($wxuser,"remark"),
                "headimgurl" => set_default($wxuser,"headimgurl"),
            );
            
            
            $subscribe_time  =  set_default($wxuser,"subscribe_time");
            if($subscribe_time){
                $user_data['subscribe_time'] = date("Y-m-d H:i:s",$subscribe_time);
            }

        }
        return $user_data;
    }
    
    /*
     * 文本消息处理
     */
    protected function _receiveText($content){
    
        //用if语句进行路由分发
        if($content == "110"){
            $res = $this->text("报警请拨110");
            return $res;
        }else if($content == "119"){
            $res = $this->text("火警请拨119");
            return $res;
        }else if(is_numeric($content)){
            $res = $this->text("你发了一个数字");
            return $res;
        }else if(in_array($content,array("王思聪","马云","王健林","刘强东","章泽天"))){
            $res = $this->text("你发了一个人");
            return $res;
        }
        #xiaojun:多客服处理
        else if(in_array($content,array("售前客服", "售前", "客服", "在线客服"))){
            $kf_account = C('KF_ACCOUNT');
            $kf_wenhou = C('KF_WENHOU');
            $this->createKFSession($this->openid,$kf_account);//创建回话
            $kefu_msg = array(
                "touser" => $this->openid,
                "msgtype" => 'text',
                "text" => array(
                    "content" => $kf_wenhou
                )
            );
            $this->sendCustomMessage($kefu_msg);//发送客服消息
            echo "";exit;//输出空串
        }else if(in_array($content,array("售后客服", "售后"))){
            $res = $this->text("请联系电话：021-31009960");
        }
    
        else{
            //按普通关键词处理
            $res = $this->_do_keyword($content);
            return $res;
        }
    
    }
    
    
    /*
     * 从数据库取关键词列表
     */
    protected function _get_keyword_list(){
        //从数据库中取出所以的关键词
        $where = array(
            "r_status" => 1,
        );
        $res = $this->keywordModel->order("id DESC")->where($where)->select();
        return $res;
    }
    
    
    /*
     * 关键词回复消息
     */
    protected function _replymsg_ready($data = null){
        if($data){
            //回复消息 $data 单条记录
            $r_type = set_default($data,'r_type');
            $reply_text = set_default($data,'reply_text');
            
            if($r_type == 1){
                //文本消息
                $res = $this->text($reply_text);
                return $res;
            }else{
                //其他类型消息
                $res = $this->text("暂时只支持图文和文本消息!");
                return $res;
            }
        }else{
            $res = $this->text("管理员请设置系统默认回复!");
            return $res;
        }
    }
    
    /*
     * 普通关键词处理
     */
    protected function _do_keyword($content){
        $klist = $this->_get_keyword_list();
      
        if($klist){
            //关键词表不为空
            foreach($klist as $k=>$v){
                $new_key[$v['id']] = $v['keyword'];
                $new_data[$v['id']] = $v;
            }
    
            //判断发送的句子是否在关键词表里(精准匹配)
            if(in_array($content, $new_key)){
                //找到了关键词
                $reply_id = array_search($content, $new_key);//取得对应的id
                $data = $new_data[$reply_id];
                //回复消息
                $res = $this->_replymsg_ready($data);
                return $res;
            }
    
            //精准匹配没匹配到,再进行模糊匹配
            //判断关键词列表是否有包含于发送的句子中的, 模糊匹配
            foreach($new_data as $k=>$v){
                // is_jingzhun 是否精准匹配,1精准匹配,0模糊匹配(默认)
                if(($v['is_jingzhun'] == 0) && (stripos($content,$v['keyword']) !== false)){
                    //匹配到了
                    $reply_id = $v['id'];
                    //回复消息
                    $res = $this->_replymsg_ready($v);
                    return $res;
                }
            }
    
            //没有匹配到,使用默认关键字defaults
            $data = $this->keywordModel->getKeyword(array("keyword"=>'defaults'));
            $res = $this->_replymsg_ready($data);
            return $res;
        }
    
        //关键词表为空
        $res = $this->_replymsg_ready();
        return $res;
    
    }
    
    /*
     * 图片消息处理
     */
    protected function _receiveImage(){
        $res = $this->text("你发的照片收到了~");
        return $res;
    }
    
    /*
     * 事件消息处理
     */
    protected function _receiveEvent(){
        $type = $this->getRev()->getRevEvent();
        $event = set_default($type,'event');
        $key = set_default($type,'key');
        
        //普通关注事件
        $sceneid = $this->getRev()->getRevSceneId();
        
        //扫码事件
        if($sceneid && ($event == "subscribe" || $event == "SCAN")){
            
            if($event == "subscribe"){
                //第一次关注
        
            }else if($event == "SCAN"){
                //已关注,再次扫码
        
            }
            
            if (is_int($sceneid)) {
                //临时二维码
                $res = $this->_int_qrcode($sceneid);
            } else {
                //永久二维码
                $res = $this->_str_qrcode($sceneid);
            }
            
            return $res;
            
        }else if($event == "subscribe"){
            //直接关注事件
            $res = $this->_subscribe();
            return $res;
            
        }else if($event == "LOCATION"){
            //上报地理位置
            return false;
            
        }else if($event == "CLICK"){
            //用户点击自定义菜单后，微信会把点击事件推送给开发者，请注意，点击菜单弹出子菜单，不会产生上报。
            //return false;
            
            
        }else if($event == "VIEW"){
            //用户点击自定义菜单后，微信会把点击事件推送给开发者，请注意，点击菜单弹出子菜单，不会产生上报。
            return false;
            
        }else if($event == "unsubscribe"){
            //取消关注
            $this->memberModel->where(array('openid' => $this->openid))->setField('subscribe',0);
            return false;
            
        }
       
        
        //转交文本消息处理
        $res = $this->_receiveText($key);
        return $res;

    }
    
    
    /*
     * 皇冠登录
     */
    protected function _king_login($sceneid){
        //处理皇冠扫码登录
        $openid = $this->openid;
        $map = array(
            'openid' => $openid
        );
        $king = $this->memberModel->where($map)->find();
        
        if($king['grade_id']<=2){
            $res = $this->text("你还不是皇冠会员哦，暂时无法登录");
        
        }else{
            $url = get_domian().'/King/login/checklogin?randid='.$sceneid.'&openid='.$openid;
            $string = "你申请了微信扫码登录，"."<a href='".$url."'>请点击确认登录</a>";
            $res = $this->text($string);
        }
        
        return $res;
    }
    
    /*
     * 临时二维码
     */
    protected function _int_qrcode($sceneid){
        
        $str_len = strlen($sceneid);
        if($str_len == 10){
            $res = $this->_king_login($sceneid);
            return $res;
        }

        return false;
    }
    
    
    /*
     * 永久二维码
     */
    protected function _str_qrcode($sceneid){
        
        $suid = $this->_store_qrcode_reply($sceneid);

        if($suid){
            //扫码得到下级
            $res = $this->_scan_team($suid);
            return $res;
        }
        
        return false;
    }
    
    /*
     * 扫码得到下级
     * $suid ,上级用户的 uid
     */
    protected function _scan_team($suid){ 
        
        //判断是否已经有上级
        $where = array(
            "openid" => $this->openid
        );
        $local_user = $this->memberModel->getMember($where);
        if(!$local_user){
            return false;
        }
        
        $where_suid = array(
            "uid" => $suid
        );
        $sinfo = $this->memberModel->getMember($where_suid);
        if(!$sinfo){
            $content = "抱歉,当前二维码已失效,请重新生成二维码!";
            $res = $this->text($content);
            return $res;
        }
        
        //普通会员可以变更推荐人
        if($local_user['refer_uid']&&$local_user['grade_id']>1){
            //已经有推荐人
            if($local_user['refer_uid'] != $suid){
                $content = "很遗憾,您已经是".$local_user['refer_nickname']."的团队成员,本次扫码无效。如有疑问,请联系客服!";
                
                $content = "欢迎加入全球伯乐商城，全球精选·自主品牌，尽在全球伯乐！点击首页，进入商城，即可开启您的购物之旅！";

                $res = $this->text($content);
                return $res;
            }else{
                $content = "恭喜您,您已成为".$local_user['refer_nickname']."的团队成员!";
                $content = "欢迎加入全球伯乐商城，全球精选·自主品牌，尽在全球伯乐！点击首页，进入商城，即可开启您的购物之旅！";

                $res = $this->text($content);
                return $res;
            }
        }else{
            //无推荐人,更新推荐人信息
            if($sinfo['uid'] == $local_user['uid']){
                $content = "您扫描的是您自己的二维码!";
                $content = "欢迎加入全球伯乐商城，全球精选·自主品牌，尽在全球伯乐！点击首页，进入商城，即可开启您的购物之旅！";

                $res = $this->text($content);
                return $res;
            }
            
            $nickname = $sinfo['realname'] ? $sinfo['realname'] : $sinfo['nickname'];
            //检查推荐人
            $res = $this->_check_sinfo($local_user,$sinfo);
            if(!$res){
                $content = "抱歉,由于系统策略限制,您无法成为".$nickname."的团队成员,请咨询客服!";
                $content = "欢迎加入全球伯乐商城，全球精选·自主品牌，尽在全球伯乐！点击首页，进入商城，即可开启您的购物之旅！";

                $res = $this->text($content);
                return $res;
            }
            
            
            $s_user = array(
                "refer_uid" => $sinfo['uid'],
                "refer_openid" => $sinfo['openid'],
                "refer_unionid" => $sinfo['unionid'],
                "refer_nickname" => $nickname,
                "regfrom" => "scangh",
                "refer_time" => date('Y-m-d H:i:s')
            );
            $r = $this->memberModel->editMember($where, $s_user);
            if($r){
                
                $where = array(
                    "openid" => $this->openid
                );
                $user_data = $this->memberModel->getMember($where);
                $this->_scanMsg($user_data);//发送模板消息
                
                $content = "恭喜您,您已成为".$nickname."的团队成员!";
                $content = "欢迎加入全球伯乐商城，全球精选·自主品牌，尽在全球伯乐！点击首页，进入商城，即可开启您的购物之旅！";

                $res = $this->text($content);
                return $res;
            }else{
                $content = "恭喜您,您已成为".$local_user['refer_nickname']."的团队成员!";
                $content = "欢迎加入全球伯乐商城，全球精选·自主品牌，尽在全球伯乐！点击首页，进入商城，即可开启您的购物之旅！";

                $res = $this->text($content);
                return $res;
            } 
        }
        
        return $res;
        
    }
    
    /*
     * 检查推荐人信息
     * $userinfo 本人
     * $sinfo 推荐人
     */
    protected function _check_sinfo($userinfo,$sinfo){

        if(empty($sinfo)){
            return false;
        }
        
        if($userinfo['uid'] ==  $sinfo['uid']){
           //推荐人不能是自己
           return false;
        }
            
        $new_refer_uid = $sinfo['refer_uid'];
        
        while($new_refer_uid){
            if($new_refer_uid == $userinfo['uid']){
                //推荐人的上级是我
                return false;
            }
            
            $where = array(
                "uid" => $new_refer_uid
            );
            $new_refer_uid = $this->memberModel->where($where)->getField('refer_uid');
        }
        
        //推荐人合法
        return true;
    }
    
    
   
    /*
     * 关注事件处理
     */
    protected  function _subscribe(){
        $data = $this->keywordModel->getKeyword(array("keyword"=>'subscribe'));
        $res = $this->_replymsg_ready($data);
        return $res;
    }
    
    
    /*
     * 地理位置消息处理
     */
    protected function _receiveLocation(){
        $res = $this->text("收到你的地址");
        return $res;
    }
    
    
    /*
     * 语音消息处理
     */
    protected function _receiveVoice(){
        $res = $this->text("收到你的语音");
        return $res;
    }
    
    /*
     * 视频消息处理
     */
    protected function _receiveVideo(){
        $res = $this->text("收到你的视频");
        return $res;
    }
    
    /*
     * 小视频消息处理
     */
    protected function _receiveShortvideo(){
        $res = $this->text("收到你的小视频");
        return $res;
    }
    
    
    /*
     * 链接消息处理
     */
    protected function _receiveLink(){
        $res = $this->text("收到你的小链接");
        return $res;
    }
    
    /*
     * 扫描店铺二维码信息回复
     */
    protected function _store_qrcode_reply($sceneid){
        $storeinfo = explode("_",$sceneid);
        if($storeinfo[0] == 'FENXIAO' && $storeinfo[1] == 'UID'){
            
            $suid = $storeinfo[2];
            $suid = intval($suid);
            if(!$suid){
                return false;
            }
            return $suid;
        }
        return false;
    }
    
    /*
     * 将会员信息写表,返回uid
     */
    protected function _add_member($memberinfo){
        //查找会员是否存在数据库中
        $openid = $memberinfo['openid'];
        if(!$openid){
            return false;
        }
        $where = array(
            "openid" => $openid
        );
        $local_user = $this->memberModel->getMember($where);
        
        if(!empty($local_user)){
            //数据库中已经存在该用户,更新用户信息
            $memberinfo['last_login_time'] = date("Y-m-d H:i:s");
            $res = $this->memberModel->editMember($where, $memberinfo);
            $uid = $local_user['uid'];
        }else{
            //数据库中不存在该用户,添加该用户到表
            $memberinfo['create_time'] = date("Y-m-d H:i:s");
            $memberinfo['last_login_time'] = date("Y-m-d H:i:s");
            /* $max = $this->memberModel->order('uid desc')->getField('uid');
            $uid = $max+7;
            $memberinfo['uid'] = $uid; */
            $this->memberModel->addMember($memberinfo);
        }
        return $uid;
    }

    
    /*
     * 扫码关注提醒
     * $userinfo 当前扫码的用户
     */
    protected function _scanMsg($userinfo){
    
        if(empty($userinfo['refer_openid'])){
            return false;
        }
    
        //发送升级模板消息
        //发送模板消息
        $msg = $this->_scanTmp($userinfo);//拼接模板消息
    
        $msgttt = array(
            "uid" => $userinfo['refer_uid'],
            "openid" => $userinfo['refer_openid'],
            "nickname" => $userinfo['refer_nickname'],
            "groupid" => -1,
            "content" => $msg,
            "send_priority" => 1,
            "create_time" => time(),
            "send_time" => time(),
            "status" => -1,
            "send_plan_time" => time()
        );
         
        $tmpmsgModel = new tmpmsgModel();
        $tmpmsgModel->addtmpmsg($msgttt);//添加消息到数据库队列
    
        return true;
    }
    


    /*
     * 拼接关注模板
     * "sharelink","scanqrcode","scangh","subscribe","import","timeline","singlemessage","groupmessage"
     */
    protected function _scanTmp($userinfo){
         
        $from = $userinfo['regfrom'];
        if($from == "sharelink"){
            $content = "你好,以下用户通过你分享的链接加入了";
        }else if($from == "scanqrcode"){
            $content = "你好,以下用户扫描了你的推广二维码";
        }else if($from == "scangh"){
            $content = "你好,以下用户扫描了你的公众号二维码";
        }else if($from == "timeline"){
            $content = "你好,以下用户通过你朋友圈的分享成进入了商城";
        }else if($from == "singlemessage"){
            $content = "你好,以下用户通过你分享的链接进入了商城";
        }else if($from == "groupmessage"){
            $content = "你好,以下用户通过你发在群中的链接进入了商城";
        }else{
            $content = "你好,以下用户关注了商城";
        }
         
    
    
        $userinfo['nickname'] = str_replace(array(",","'","\"","\\","\/","`"),array("，","＂","＂","","",""),$userinfo['nickname']);//转义
        $userinfo['refer_nickname'] = str_replace(array(",","'","\"","\\","\/","`"),array("，","＂","＂","","",""),$userinfo['refer_nickname']);//转义
         
        $userinfo['nickname'] = str_replace(array("\r\n", "\r", "\n"), "", $userinfo['nickname']);
        $userinfo['nickname'] = str_replace(PHP_EOL, '', $userinfo['nickname']);
        $userinfo['refer_nickname'] = str_replace(array("\r\n", "\r", "\n"), "", $userinfo['refer_nickname']);
        $userinfo['refer_nickname'] = str_replace(PHP_EOL, '', $userinfo['refer_nickname']);
    
        $tmp_id = $this->tmpl['XIAJI_REG']['tmp_id'];
        $color = $this->tmpl['XIAJI_REG']['color'];
    
        $url = get_domain()."/mobile/user/daili?dj=1";
        $footer ='\\n\\n'."点击查看详情...";
        $msg = array(
            "touser" => $userinfo['refer_openid'],
            "template_id" => $tmp_id,
            'url' => $url,
            "topcolor" => $color,
            'data' => array(
                'first' => array(
                    'value' => urlencode($content.'\\n'),
                    'color' => $color
                ),
                'keyword1' => array(
                    'value' => urlencode($userinfo['nickname']),//扫码人
                    'color' => $color,
                ),
                'keyword2' => array(
                    'value' => urlencode(date("Y-m-d H:i:s")),//注册时间
                    'color' => $color,
                ),
                'remark' => array(
                    'value' => urlencode($footer),
                    'color' => $color,
                ),
            ),
        );
    
        return $msg = urldecode(json_encode($msg));
    }
    
    
    
}